package com.xtjc.recsyslog.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class NettyServer {

    @Autowired
    private NettyServerInitializer nettyServerInitializer;

    public void serverRun() {
        //循环组接收连接，不进行处理,转交给下面的线程组
        //boss线程监听端口，worker线程负责数据读写
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 把两个线程组加入进来
            bootstrap.group(boss, worker);
            // 指定使用NioServerSocketChannel这种类型通道
            bootstrap.channel(NioServerSocketChannel.class);
            // 一定要使用去绑定具体的事件处理器
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024);// 默认128 Socket参数，服务端接受连接的队列长度，如果队列已满，客户端连接将被拒绝。默认值，Windows为200，其他为128。
            bootstrap.option(ChannelOption.SO_RCVBUF, 1024 * 1024);
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);//Socket参数，连接保活，默认值为False。启用该功能时，TCP会主动探测空闲连接的有效性。
            bootstrap.childOption(ChannelOption.TCP_NODELAY, true);//TCP参数，立即发送数据，默认值为Ture。
            bootstrap.handler(new LoggingHandler(LogLevel.INFO));
            bootstrap.childHandler(nettyServerInitializer);

            ChannelFuture future = bootstrap.bind(17001).sync();
            log.info("server start ......");
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}